import express from 'express';
import {
  addUser,
  changeUserAvatar,
  changeUserReputation,
  deleteUserById,
  queryIsFollowed,
  queryPopularUser,
  queryPopularUserByTag,
  queryUserBeFollowed,
  queryUserById,
  queryUserByUserName,
  queryUserFollowed,
  queryUsersByLevel,
  userEdit,
  userFollow,
  userUnFollow,
} from '../service/user.js';
import { hash } from '../libs/hash.js';
import { decrypt } from '../libs/decrypt.js';
import { confirmAccount } from '../interceptors/user.js';
import { v4 } from 'uuid';
import redis from '../db/cache.js';
import { queryTagsByUser } from '../service/question.js';
import { insertionSort } from '../utils/sort.js';
import { removeFile } from '../utils/file.js';

const userRouter = express.Router();

const keyStr = 'KI6859d&9lF@AA4$';

userRouter.post('/register', confirmAccount, (req, res) => {
  // console.log(req.body)
  const hashPassword = hash(keyStr, req.body.password);
  const userInfo = {
    user_name: req.body.account,
    user_password: hashPassword.portalReq,
    user_permission: req.body.level,
  };
  addUser(userInfo)
    .then((data) => {
      res.send(data);
    })
    .catch((err) => {
      console.log(err);
    });
});

userRouter.post('/login', (req, res) => {
  queryUserByUserName(req.body.account).then((data) => {
    // 验证账号是否存在
    if (data.length) {
      const userInfo = data[0].dataValues;
      // 密码解密
      userInfo.user_password = decrypt(keyStr, userInfo.user_password);
      // 验证密码
      if (userInfo.user_password === req.body.password) {
        // 创建redis存储
        const token = v4();
        redis.set(token, userInfo.user_id, {
          EX: 12 * 60 * 60,
          // EX: 10
        });
        res.send({
          resCode: 200,
          message: '成功！',
          data: {
            token,
          },
        });
      } else {
        res.send({ resCode: 401, message: '密码错误！' });
      }
    } else {
      res.send({ resCode: 404, message: '帐号不存在！' });
    }
  });
});

userRouter.get('/authCookie', async (req, res) => {
  if (req.headers.authorization) {
    const session = await redis.get(req.headers.authorization);
    if (session) {
      res.send({ isValid: true });
    } else {
      res.send({ isValid: false });
    }
  }
});

userRouter.get('/queryUserByAuth', async (req, res) => {
  let result;
  if (req.headers.authorization) {
    result = await queryUserById(await redis.get(req.headers.authorization));
  } else {
    res.send({ resCode: 401, message: '未授权' });
    return;
  }
  if (result.length) {
    if (result[0].user_prefer) {
      result[0].user_prefer = result[0].user_prefer.split(',');
    } else {
      result[0].user_prefer = [];
    }
    res.send({
      resCode: 200,
      data: result[0],
    });
  } else {
    res.send({
      resCode: 404,
      message: '未找到用户...',
    });
  }
});

userRouter.get('/queryUserById', (req, res) => {
  queryUserById(req.query.id).then((data) => {
    if (data.length > 0) {
      if (data[0].user_prefer) {
        data[0].user_prefer = data[0].user_prefer.split(',');
      } else {
        data[0].user_prefer = [];
      }
      res.send({ resCode: 200, data: data[0] });
    } else {
      res.send({ resCode: 404, message: '找不到用户' });
    }
  });
});

userRouter.post('/userReputationUp', (req, res) => {
  changeUserReputation(req.body.id, 1)
    .then(() => {
      res.send({ resCode: '200', message: '成功' });
    })
    .catch(() => {
      res.send({ resCode: '500', message: '失败' });
    });
});

userRouter.post('/userReputationDown', (req, res) => {
  changeUserReputation(req.body.id, -1)
    .then(() => {
      res.send({ resCode: '200', message: '成功' });
    })
    .catch(() => {
      res.send({ resCode: '500', message: '失败' });
    });
});

userRouter.get('/queryPopularUser', async (req, res) => {
  queryPopularUser()
    .then((data) => {
      res.send({ resCode: '200', data });
    })
    .catch((err) => {
      console.log('获取用户热度榜错误', err);
    });
});

userRouter.get('/queryUserPrefer', async (req, res) => {
  let result = await queryTagsByUser(req.query.userId);
  result = result.filter((item) => item.question_tags !== null);
  const tags = [];

  result = result.reduce((result, currentVal) => {
    let currentTags = currentVal.question_tags;
    currentTags = currentTags.split(',');
    for (const value of currentTags) {
      result.push(value);
    }
    return result;
  }, tags);

  result = result.reduce((result, currentVal) => {
    if (Object.hasOwn(result, currentVal)) {
      result[currentVal] += 1;
    } else {
      result[currentVal] = 1;
    }
    return result;
  }, {});

  result = Object.entries(result);

  // 插入排序选出前五个
  insertionSort(result, 'DESC');
  if (result.length > 5) {
    result = result.slice(0, 5);
  }

  res.send({ resCode: 200, data: result });
});

userRouter.post('/changeUserAvatar', (req, res) => {
  if (req.body.user_id && req.body.path) {
    let oldAvatar;
    if ((req.body.oldPath !== null) | '') {
      oldAvatar = req.body.oldPath;
    }
    changeUserAvatar(req.body.user_id, req.body.path)
      .then((data) => {
        if (!((oldAvatar === null) | undefined)) {
          removeFile(oldAvatar);
        }
        res.send({ resCode: '200', message: '修改成功' });
      })
      .catch(() => {
        res.send({ resCode: '500', message: '修改失败' });
      });
  }
});

userRouter.post('/userEdit', (req, res) => {
  const userInfo = { ...req.body };
  userInfo.user_prefer = userInfo.user_prefer.join(',');
  userEdit(userInfo)
    .then((data) => {
      res.send({ resCode: 200, message: '修改成功' });
    })
    .catch(() => {
      res.send({ resCode: 500, message: '修改失败' });
    });
});

userRouter.get('/queryPopularUserByTag', (req, res) => {
  const { tag } = req.query;
  if (tag.replace(/\s+/g, '') === '') {
    res.send({ resCode: 500, message: '无意义的参数' });
  } else {
    queryPopularUserByTag(tag)
      .then((data) => {
        data = data.map((item) => {
          item.user_prefer = item.user_prefer.split(',');
          return item;
        });
        res.send({ resCode: 200, data });
      })
      .catch((err) => {
        console.log(err);
        res.send({ resCode: 500, message: '查询失败' });
      });
  }
});

userRouter.post('/userFollow', (req, res) => {
  const { follower, followed } = req.body;
  if (follower && followed) {
    userFollow(follower, followed)
      .then(() => {
        res.send({ resCode: 200, message: '关注成功' });
      })
      .catch(() => {
        res.send({ resCode: 500, message: '关注失败' });
      });
  }
});

userRouter.post('/userUnFollow', (req, res) => {
  const { follower, followed } = req.body;
  if (follower && followed) {
    userUnFollow(follower, followed)
      .then(() => {
        res.send({ resCode: 200, message: '已取消关注' });
      })
      .catch(() => {
        res.send({ resCode: 500, message: '取消关注失败' });
      });
  }
});

userRouter.get('/queryIsFollowed', (req, res) => {
  const { follower, followed } = req.query;
  if (follower && followed) {
    queryIsFollowed(follower, followed)
      .then((data) => {
        if (data.length > 0) {
          res.send({ resCode: 200, data });
        } else {
          res.send({ resCode: 404, message: '未关注' });
        }
      })
      .catch((err) => {
        console.log(err);
        res.send({ resCode: 500, message: '查询失败' });
      });
  }
});

userRouter.get('/queryUserFollowed', (req, res) => {
  const { follower } = req.query;
  if (follower) {
    queryUserFollowed(follower)
      .then((data) => {
        data = data.map((item) => {
          if (item.dataValues.user_prefer) item.dataValues.user_prefer = item.dataValues.user_prefer.split(',');
          return item;
        });
        res.send({ resCode: 200, data });
      })
      .catch((err) => {
        console.log(err);
        res.send({ resCode: 500, message: '查询失败' });
      });
  }
});

userRouter.get('/queryUserBeFollowed', (req, res) => {
  const { followed } = req.query;
  if (followed) {
    queryUserBeFollowed(followed)
      .then((data) => {
        data = data.map((item) => {
          if (item.dataValues.user_prefer) item.dataValues.user_prefer = item.dataValues.user_prefer.split(',');
          return item;
        });
        res.send({ resCode: 200, data });
      })
      .catch((err) => {
        console.log(err);
        res.send({ resCode: 500, message: '查询失败' });
      });
  }
});

userRouter.get('/queryUsers', async (req, res) => {
  const { level } = req.query;
  const result = await queryUsersByLevel(level);

  res.send({ resCode: 200, data: result });
});

userRouter.post('/delUser', (req, res) => {
  const { user_id } = req.body;
  deleteUserById(user_id).then(() => {
    res.send({ resCode: 200, message: '删除成功' });
  });
});

export default userRouter;
